package com.ch04.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Jane
 * @date 2024-05-29 17:19
 */

public class Interceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("**********************preHandle1");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        if(request.getSession()!=null){
            if(request.getSession().getAttribute("backendUser")==null){
                PrintWriter out = response.getWriter();
                out.print("<script>alert('请先登录');location.href='"+request.getContextPath()+"/backend/login'</script>");
                out.flush();
                out.close();
            }
        }
        System.out.println("**********************postHandle1"+request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("**********************afterCompletion1");
    }
}
